import json
import time

import requests
import websocket
from loguru import logger


def post_flag(deviceName, flag):
    logger.info("设备：【{}】，标志：【{}】".format(deviceName, flag))
    url = "http://1.95.166.150:8997/api/v1/device/changeGateResult/{}/{}".format(deviceName, flag)
    requests.get(url)
    logger.info("执行任务完成：【{}】", url)


def get_task_server():
    url = "http://1.95.166.150:8997/api/v1/device/getTask"
    response = requests.get(url)
    task_obj = json.loads(response.text)
    if task_obj['data'] is not None:
        logger.info("执行任务：【{}】", task_obj['data'])
        send_msg(task_obj['data']['deviceName'], task_obj['data']['ip'])


def send_msg(device_name, ip):
    # 创建 WebSocket 客户端对象
    ws = websocket.WebSocket()
    # 连接到 WebSocket 服务器
    ws.connect("ws://{}:8555/api".format(ip))
    # 发送消息
    ws.send('{"command":"CBSwitchNext_Multi","arguments":{"devicename":"' + device_name + '"}}')
    result_text = ws.recv()
    logger.info("接收返回：【{}】", result_text)
    result_data = json.loads(result_text)
    if result_data['data']['invoke_command'] == "CBSwitchNext_Multi":
        flag = -1
        if result_data['data']['state']:
            flag = 99
        post_flag(device_name, flag)
    # 关闭连接
    ws.close()


while 1:
    try:
        logger.info("获取任务...")
        get_task_server()
    except:
        logger.error("获取任务失败")
    time.sleep(5)
